package com.cema.manage.project.manage.users.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cema.manage.common.utils.StringUtils;
import com.cema.manage.framework.web.controller.BaseController;
import com.cema.manage.framework.web.domain.Message;
import com.cema.manage.framework.web.page.TableDataInfo;
import com.cema.manage.project.manage.friend.domain.Friend;
import com.cema.manage.project.manage.friend.service.IFriendService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.domain.UsersVo;
import com.cema.manage.project.manage.users.service.IUsersService;
import com.cema.manage.project.system.user.domain.UserRole;
import com.cema.manage.project.system.user.mapper.UserRoleMapper;
import com.cema.manage.redis.RedisService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户账号 信息操作处理
 *
 * @author reasahi
 * @date 2024-07-08
 */
@Controller
@RequestMapping("/manage/users")
public class UsersController extends BaseController {
    private String prefix = "manage/users";

    @Resource
    private IUsersService usersService;

    @Resource
    private IFriendService iFriendService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RedisService redisService;

    @GetMapping()
    @RequiresPermissions("manage:users:view")
    public String users() {
        return prefix + "/users";
    }

    /**
     * 查询用户账号列表
     */
    @RequiresPermissions("manage:users:list")
    @ResponseBody
    @PostMapping("/list")
    public TableDataInfo list(UsersVo usersVo) {
        startPage();
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        //验证是否是代理
        Integer plUserId = getUser().getPlUserId();

        if (ObjectUtil.isNotNull(plUserId)) {
            usersVo.setUsParentId(plUserId);
        }
        entityWrapper.setEntity(BeanUtil.toBean(usersVo, Users.class));
        String nickname = usersVo.getUsNickname();
        if (StrUtil.isNotEmpty(nickname)) {
            entityWrapper.like("nickname", nickname, SqlLike.RIGHT);
        }
        Date loginTime = usersVo.getEndLoginTime();
        if (ObjectUtil.isNotNull(loginTime)) {
            entityWrapper.between("login_time", usersVo.getStartLoginTime(), loginTime);
        }
        Date endTime = usersVo.getEndTime();
        if (ObjectUtil.isNotNull(endTime)) {
            entityWrapper.between("create_time", usersVo.getStartTime(), endTime);
        }
        setEntity(entityWrapper, "money_gold_coin", usersVo.getStartGoldCoin(), usersVo.getEndGoldCoin());
        setEntity(entityWrapper, "money_red_packet", usersVo.getStartRedPacket(), usersVo.getEndRedPacket());
        setEntity(entityWrapper, "sign_in_number", usersVo.getStartSignInNumber(), usersVo.getEndSignInNumber());
        setEntity(entityWrapper, "sign_id_day_number", usersVo.getStartSignIdDayNumber(), usersVo.getEndSignIdDayNumber());
        setEntity(entityWrapper, "login_day_number", usersVo.getStartLoginDayNumber(), usersVo.getEndLoginDayNumber());
        setEntity(entityWrapper, "login_in_day_number", usersVo.getStartLoginDayNumber(), usersVo.getEndLoginDayNumber());
        entityWrapper.orderBy("create_time", false);
        List<Users> list = usersService.selectList(entityWrapper);
        return getDataTable(list);
    }

    private void setEntity(EntityWrapper<Users> entityWrapper, String column, String start, String end) {
        if (StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)) {
            entityWrapper.between(column, start, Integer.parseInt(end) + 1);
        }
        if (StrUtil.isNotEmpty(start)) {
            entityWrapper.ge(column, start);

        }
        if (StrUtil.isNotEmpty(end)) {
            entityWrapper.le(column, end);
        }
    }

    /**
     * 新增用户账号
     */
    @RequiresPermissions("manage:users:add")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 修改用户账号
     */
    @RequiresPermissions("manage:users:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, Model model) {
        Users users = usersService.selectById(id);
        model.addAttribute("users", users);
        return prefix + "/edit";
    }

    @RequiresPermissions("manage:users:resetKickback")
    @GetMapping("/kickback/{id}")
    public String resetKickback(@PathVariable("id") Long id, Model model) {
        Users users = usersService.selectById(id);
        model.addAttribute("users", users);
        return prefix + "/resetKickback";
    }

    @RequiresPermissions("manage:users:resetUsParentId")
    @GetMapping("/usParentId/{id}")
    public String resetUsParentId(@PathVariable("id") Long id, Model model) {
        Users users = usersService.selectById(id);
        model.addAttribute("users", users);
        return prefix + "/resetUsParentId";
    }

    /**
     * 保存用户账号
     */
    @RequiresPermissions("manage:users:save")
    @PostMapping("/save")
    @ResponseBody
    public Message save(Users users) {
        Integer id = users.getId();
        if (StringUtils.isNotNull(id)) {
            String phone = users.getAfbPhone();
            if (StrUtil.isEmpty(phone)) {
                users.setAfbPhone("");
                users.setAfbName("");
            }
            if (usersService.updateById(users)) {
                return Message.success();
            }
            return Message.error();
        } else {
            if (usersService.insert(users)) {
                return Message.success();
            }
            return Message.error();
        }
    }

    /**
     * 保存用户账号
     */
    @RequiresPermissions("manage:users:save")
    @PostMapping("/us_parent_id")
    @ResponseBody
    public Message resetUsParentId(Users users) {
        EntityWrapper<Friend> friendEntityWrapper = new EntityWrapper<>();
        friendEntityWrapper.eq("us_id", users.getId());
        Friend friend = iFriendService.selectOne(friendEntityWrapper);
        Integer usParentId = users.getUsParentId();
        if (ObjectUtil.isNotNull(usParentId)) {
            if (ObjectUtil.isNotNull(friend) && friend.getFusId().equals(usParentId)) {
                return Message.success();
            }
            if (ObjectUtil.isNotNull(friend)) {
                friend.setFusId(usParentId);
                boolean flagFriend = iFriendService.updateById(friend);
                if (!flagFriend) {
                    return Message.error();
                }
            } else {
                friend = new Friend();
                friend.setFusId(usParentId);
                friend.setUsId(users.getId());
                boolean flagFriend = iFriendService.insert(friend);
                if (!flagFriend) {
                    return Message.error();
                }
            }
            Users updateUser = new Users();
            updateUser.setId(users.getId());
            updateUser.setUsParentId(usParentId);
            boolean flagUsers = usersService.updateById(updateUser);
            if (flagUsers) {
                return Message.success();
            }
            return Message.error();

        }
        if (ObjectUtil.isNull(friend)) {
            return Message.success();
        }
        boolean boolFriend = iFriendService.deleteById(friend.getId());
        Integer count = usersService.updateUsParentId(users.getId());
        if (boolFriend && count > 0) {
            return Message.success();
        }
        return Message.error();
    }

    /**
     * 保存用户账号
     */
    @RequiresPermissions("manage:users:save")
    @PostMapping("/kickback")
    @ResponseBody
    public Message resetUsKickback(Users users) {
        EntityWrapper<UserRole> userRoleEntityWrapper = new EntityWrapper<>();
        userRoleEntityWrapper.eq("user_id", getUser().getUserId());
        List<UserRole> userRoleList = userRoleMapper.selectList(userRoleEntityWrapper);
        int countProxy = userRoleList.stream().filter(userRole -> userRole.getRoleId() == 4).collect(Collectors.toList()).size();
        Integer kickback = users.getKickback();

        if (countProxy > 0) {
            Users usersProxy = usersService.selectById(getUser().getPlUserId());
            if (kickback > usersProxy.getKickback()) {
                return Message.error();
            }
        }
        if (ObjectUtil.isNotNull(kickback)) {
            Users updateUser = new Users();
            updateUser.setId(users.getId());
            updateUser.setKickback(kickback);
            boolean flagUsers = usersService.updateById(updateUser);
            if (flagUsers) {
                //更新缓存
                Users redisUser = usersService.selectById(users.getId());
                redisService.set(redisUser.getDeviceId(), redisUser);
                return Message.success();
            } else {
                return Message.error();
            }
        }
        int count = usersService.updateKickback(users.getId());
        users.setKickback(null);
        redisService.set(users.getOpenid()+users.getDeviceId(), users);
        return count > 0 ? Message.success() : Message.error();
    }

    /**
     * 删除用户账号
     */
    @RequiresPermissions("manage:users:remove")
    @PostMapping("/remove/{id}")
    @ResponseBody
    public Message remove(@PathVariable("id") Integer id) {
        if (usersService.deleteById(id)) {
            return Message.success();
        }
        return Message.error();
    }

    /**
     * 批量删除用户账号
     */
    @RequiresPermissions("manage:users:batchRemove")
    @PostMapping("/batchRemove")
    @ResponseBody
    public Message remove(@RequestParam("ids[]") Integer[] ids) {
        List list = new ArrayList();
        for (Integer n : ids) {
            list.add(n);
        }
        if (usersService.deleteBatchIds(list)) {
            return Message.success();
        }
        return Message.error();
    }

}
